/*
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at
 
 http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
 */

//
//  MainViewController.h
//  HelloWorld
//
//  Created by ___FULLUSERNAME___ on ___DATE___.
//  Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.
//

#import "MainViewController.h"
#import "CDVWebServer.h"
#import "AFHTTPRequestOperation.h"
#import "ZipArchive.h"
#import "SplashView.h"
#import "Reachability.h"
#import "SoundController.h"


typedef void (^NetResult) (id ResponseObject);

//#define KEYVERSIONTEMP  @"versionTemp"
#define KEYVERSIONPOSITON   @"www/versionPosition"
#define KEYVERSION          @"version"
#define KEYURL              @"url"
#define KEYSPLASHHIDE       @"KeySplashHide"
#define KEYSPLASHSHOW       @"keySplashShow"
#define KEYBOOLRELOAD       @"boolReload"
#define KEYVERSIONURL       @"http://120.24.55.7:9191/download/version.json"


@interface MainViewController ()
@property (strong, nonatomic)id             jsonObject;
@property(strong, nonatomic)CDVWebServer    *webServer;
@property(strong,nonatomic)SplashView       *splash;
@property (nonatomic) Reachability *        hostReachability;
//@property (nonatomic, strong)SoundController *sound;
@end

@implementation MainViewController

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
    // UIStatusBarStyleDefault = 0 黑色文字，浅色背景时使用
    // UIStatusBarStyleLightContent = 1 白色文字，深色背景时使用
}

- (BOOL)prefersStatusBarHidden
{
    return NO; // 返回NO表示要显示，返回YES将hiden
}

- (id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }
    return self;
}

- (id)init
{
    self = [super init];
    if (self) {
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
}

#pragma mark View lifecycle

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.webView.scrollView.bounces = NO;
    self.webView.dataDetectorTypes = UIDataDetectorTypeNone;
    
//    CGRect rectWeb = self.webView.frame;
//    if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 7.0) {
//        [self.view setBackgroundColor:[UIColor blackColor]];
//        CGRect frameRect = [[UIApplication sharedApplication]statusBarFrame];
//        CGRect screenBoundsWindow = CGRectMake(rectWeb.origin.x,
//                                               rectWeb.origin.y+frameRect.size.height,
//                                               rectWeb.size.width,
//                                               rectWeb.size.height-frameRect.size.height);
//        self.webView.frame =screenBoundsWindow;
//    
//    }
    
    //splashView
    SplashView *splash = [[SplashView alloc]initWithFrame:self.webView.frame];
    splash.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
    
    [self.view addSubview:splash];
    self.splash =splash;
    [self.splash show];
    [self.splash setViewFrame:self.webView.frame];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(webServerSuccess:)
                                                 name:KEYPLUGINWEBSERVERSUCCESS
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(webServerfail:)
                                                 name:KEYPLUGINWEBSERVERFAILE
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(webServerStartOk)
                                                 name:KEYSPLASHHIDE
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(splashShow)
                                                 name:KEYSPLASHSHOW
                                               object:nil];

    //net 监听
     [[NSUserDefaults standardUserDefaults]setBool:true forKey:KEYBOOLRELOAD];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:)
                                                  name:kReachabilityChangedNotification
                                                object:nil];
    NSString *remoteHostName = @"www.apple.com";
    self.hostReachability = [Reachability reachabilityWithHostName:remoteHostName];
	[self.hostReachability startNotifier];

    
#ifdef DEBUG      
    self.webServer = [[CDVWebServer alloc]init];
    [self.webServer startWebServer];
#else
    [self startSeverIfHaveUpdate];
#endif

    
//    self.webServer = [[CDVWebServer alloc]init];
//    
//    [self.webServer startWebServer];

    // Do any additional setup after loading the view from its nib.
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(willGoTo:)
                                                 name:@"CDVGOTOCONTROLLER"
                                               object:nil];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    [[NSNotificationCenter defaultCenter]removeObserver:KEYPLUGINWEBSERVERSUCCESS];
    [[NSNotificationCenter defaultCenter]removeObserver:KEYPLUGINWEBSERVERFAILE];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:@"CDVGOTOCONTROLLER"
                                                  object:nil];
//    [[NSNotificationCenter defaultCenter]removeObserver:KEYPLUGINWEBSERVERSUCCESS];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}
//ios6 以后
-(NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}

- (BOOL)shouldAutorotate{
    return YES;
}


#pragma mark UIWebDelegate implementation

-(void)splashShow
{
 [self.splash show];
}
-(void)webServerStartOk
{
    [self.splash hide];
}

- (void)webViewDidFinishLoad:(UIWebView*)theWebView
{
    // Black base color for background matches the native apps
    theWebView.backgroundColor = [UIColor blackColor];
    
    return [super webViewDidFinishLoad:theWebView];
}
#pragma mark UIWebServeRefresh implementation

- (void) webServerSuccess:(NSNotification *)notification
{
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:notification.object]]];
    NSLog(@"加载网页%@", notification.object);
    
}

- (void) webServerfail:(NSNotification *)notification
{
    ////web server fail
    
}

#pragma mark http

- (void) reachabilityChanged:(NSNotification *)note
{
     Reachability* curReach = [note object];
     NetworkStatus status = [curReach currentReachabilityStatus];
    if (status != NotReachable)
    {
        
        if (![[NSUserDefaults standardUserDefaults]boolForKey:KEYBOOLRELOAD])
        {
            [self startSeverIfHaveUpdate];
        }
    }
 
}


//startServe if web have new update else no update
-(void)startSeverIfHaveUpdate
{
    [[NSUserDefaults standardUserDefaults]setBool:true forKey:KEYBOOLRELOAD];
    //get version
    NSString *strLibPah = [NSHomeDirectory() stringByAppendingPathComponent:@"Library"];
    NSString *strVersionPath =[NSString stringWithFormat:@"%@/%@",strLibPah,KEYVERSIONPOSITON];
    
    //判断是否第一次
    BOOL boolversionExit= [[NSFileManager defaultManager]fileExistsAtPath:strVersionPath];
    if (!boolversionExit)
    {
        [self getZipFileVersionWithNetResponse:^(id ResponseObject) {
            NSDictionary *dicVersion = [self getJsonDictionaryWithJsonData:ResponseObject];
            self.jsonObject = ResponseObject;
            
            //get url
            NSString *urlPath = [dicVersion objectForKey:KEYURL];
            
            [self StartServerWithGetOutPutPath:[NSString stringWithFormat:@"%@/%@",strLibPah,[self fileNameFromUrlString:urlPath]]
                                        getUrl:urlPath];
        }];
        
    }
    else
    {
        
        [self getZipFileVersionWithNetResponse:^(id ResponseObject) {
            
            NSDictionary *dicVersion = [self getDictionaryWithJSONPath:strVersionPath];
            NSString *strVersion = [dicVersion objectForKey:KEYVERSION];
            
            NSDictionary *dicVersionTemp = [self getJsonDictionaryWithJsonData:ResponseObject];
            NSString *strVersionTemp = [dicVersionTemp objectForKey:KEYVERSION];
            //比较当前版本号
            if ([self CompareA:strVersionTemp thanBigB:strVersion])
            {
                self.jsonObject = ResponseObject;
                
                //get url
                NSString *urlPath= [dicVersionTemp objectForKey:KEYURL];
                
                [self StartServerWithGetOutPutPath:[NSString stringWithFormat:@"%@/%@",strLibPah,[self fileNameFromUrlString:urlPath]]
                                            getUrl:urlPath];
            
            }
            else
            {
                //start Server
                self.webServer = [[CDVWebServer alloc]init];
                [self.webServer startWebServer];
            }
            
        }];
    }


}

//getzipFile uzipFile start sever
-(void)StartServerWithGetOutPutPath:(NSString*)filePath getUrl:(NSString*)url
{
    
    [self getZipWWWWithOutPutPath:filePath withGetUrl:url withNetResponse:^(id ResponseObject) {
    
    //解压
    ZipArchive* zip = [[ZipArchive alloc] init];
    if( [zip UnzipOpenFile:filePath] )
    {
        BOOL ret = [zip UnzipFileTo:[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] overWrite:YES];
        if( NO==ret )
        {
            NSLog(@"betta_uzip error");
        }
        [zip UnzipCloseFile];
        
         NSError *error =nil;
        [[NSFileManager defaultManager]removeItemAtPath:filePath error:&error];
        //copyPhonegap
        NSArray *arrayPath= @[@"www/cordova_plugins.js",@"www/cordova.js",@"www/plugins",@"www/phonegap.js"];
        NSString *strLibaryPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library"];
        for (NSString *strPathItem in arrayPath) {
            NSString *jsPath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:strPathItem];
          
            
            if (![[NSFileManager defaultManager]fileExistsAtPath:jsPath]) {
                NSLog(@"betta_not exit");
            }
            
            [[NSFileManager defaultManager]copyItemAtPath:jsPath
        toPath:[strLibaryPath stringByAppendingPathComponent:strPathItem]
                                                    error:&error];
            NSLog(@"betta_copy%@",error);
        }
        
        NSString *strVersionPath =[NSString stringWithFormat:@"%@/%@",strLibaryPath,KEYVERSIONPOSITON];
        [self.jsonObject writeToFile:strVersionPath atomically:YES];
        //start Server
        self.webServer = [[CDVWebServer alloc]init];
        [self.webServer startWebServer];
        
        }
}];
}

//download zip www
-(void)getZipWWWWithOutPutPath:(NSString*)filePath  withGetUrl:(NSString*)url withNetResponse:(NetResult)result
{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]
                                             cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                         timeoutInterval:3.0];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Successfully downloaded www file to %@", responseObject);
        result(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"betta_GetWWWError: %@", error);
        [self alertNetNotConnnect];
        
        [[NSUserDefaults standardUserDefaults]setBool:false forKey:KEYBOOLRELOAD];

    }];
    
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        
        float percent = (float)totalBytesRead/(float)totalBytesExpectedToRead*100;
        NSLog(@"betta_%1.2lld ____%1.2lld",totalBytesRead,totalBytesExpectedToRead);
    }];
    
    [operation start];
}

//download version
-(void)getZipFileVersionWithNetResponse:(NetResult)result
{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:KEYVERSIONURL]
                                             cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                         timeoutInterval:3.0];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"betta_Successfully downloaded file to %@", responseObject);
        result(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"betta_GetZipError: %@", error);
        [self alertNetNotConnnect];
        
        [[NSUserDefaults standardUserDefaults]setBool:false forKey:KEYBOOLRELOAD];
    
    }];
    
    [operation start];
}

//getDictionaryWithJsonData
-(NSDictionary*)getJsonDictionaryWithJsonData:(NSData*)jsonData
{
    NSError *error = nil;
    id jsonobject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    if (error)
    {
        NSLog(@"betta_json 解析错误");
    }
    
    if ([jsonobject isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *jsonDir = (NSDictionary*)jsonobject;
        return jsonDir;
    }
    
    return NULL;
}

//getDictionaryWithFile
-(NSDictionary*)getDictionaryWithJSONPath:(NSString*)path
{
    NSData *dataVersion = [NSData dataWithContentsOfFile:path];
    NSDictionary *dicJson = [self getJsonDictionaryWithJsonData:dataVersion];
    return dicJson;
}

//compare version
-(BOOL)CompareA:(NSString*)big thanBigB:(NSString*)smaller
{
    if ([smaller compare:big options:NSNumericSearch] == NSOrderedAscending) {
        // have new version
        return YES;
    }
    return NO;
}

//getFileName
- (NSString *)fileNameFromUrlString:(NSString *)urlString
{
    NSArray *components = [urlString componentsSeparatedByString:@"/"];
    return [components lastObject];
}

//alertNet
-(void)alertNetNotConnnect
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"message"
                                                message:@"No internet connection. Please check your network."
                                               delegate:nil
                                      cancelButtonTitle:@"cancel"
                                      otherButtonTitles:nil];
    [alert show];

}

- (void) willGoTo:(NSNotification *)nofity {
    if ([nofity.object isEqualToString:@"SOUND"]) {
//        self.sound = [[SoundController alloc] initWithNibName:@"SoundController"
//                                                       bundle:nil];
//        [self.navigationController pushViewController:self.sound
//                                             animated:YES];
    }
}

- (void) dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:@"CDVGOTOCONTROLLER"
                                                  object:nil];
}


@end

@implementation MainCommandDelegate

/* To override the methods, uncomment the line in the init function(s)
 in MainViewController.m
 */

#pragma mark CDVCommandDelegate implementation

- (id)getCommandInstance:(NSString*)className
{
    return [super getCommandInstance:className];
}

/*
 NOTE: this will only inspect execute calls coming explicitly from native plugins,
 not the commandQueue (from JavaScript). To see execute calls from JavaScript, see
 MainCommandQueue below
 */
- (BOOL)execute:(CDVInvokedUrlCommand*)command
{
    return [super execute:command];
}

- (NSString*)pathForResource:(NSString*)resourcepath;
{
    return [super pathForResource:resourcepath];
}

@end

@implementation MainCommandQueue

/* To override, uncomment the line in the init function(s)
 in MainViewController.m
 */
- (BOOL)execute:(CDVInvokedUrlCommand*)command
{
    return [super execute:command];
}

@end
